import getopt
import sys
from serial.tools import list_ports
from thread_com import  thread_com
from thread_text_com import  thread_text_com
def thread_main(argv):                #实现的class_serial.py的终端操作函数
    text_num=0
    filename=""
    try:
        opts,args=getopt.getopt(argv,"hpf:c:t:",["help","port","filename=","com_port=","--test="])         # test 的话指定测试的次数，传输文件后等待下位机reset之后继续传输次数
    except getopt.GetoptError:
        print('Error: class_serila.py args is wrong , please input class_serila.py -h for help')
        print('   or: class_serial.py --help for help')
        sys.exit(2)
    for opt,arg in opts:
        if opt in ("-h","--help"):
            print("-------------------------------------------------------------------------------------------------------------------------")
            print("The use options of class_serial.py are as follows:")
            print("   main.py -f <filename> -c <com_port1> <com_port2> <com_port3> ......")
            print("   or: main.py --filename=<filename> --com_port=<com_port1> <com_port2> <com_port3> ......")
            print("   You can user class_serila.py -p  or  class_serial --port for looking the com port in computer.")
            print("   You can user class_serial.py -t <text-number> or class_serial.py --test=<text-number> user to text the process.")
            print("   If you want to user test , please user the order:")
            print("       class_serial.py -f <filename> -t <text-number> -c <com_port1> <com_port2> <com_port3> ......")
            print("       the <text-number> is the times of testing restart and process ......")
            print("-------------------------------------------------------------------------------------------------------------------------")
        elif opt in ("-p","--port"):
            port_list_name = [comport.device for comport in list_ports.comports()]
            print("  The computer the port of com userfully is: ")
            print("--"+str(port_list_name))
        elif opt in ("-f","--filename"):
            filename=arg
            print("the file {} is upload".format(arg))
        elif opt in ("-c","--com_port"):
            args.append(arg)
            if text_num==0:                      #不需要进行测试，因此直接将忽略text_num即可
                app=thread_com(args,filename)
                #print(filename)
                app.begin()
                print("the com_ports picked are: "+str(args))
            else:                                    #需要进行测试，调用测试线程text_num即可
                print("the com_ports picked are: "+str(args)+" and the test time is {}".format(text_num))
                temp=thread_text_com(args,filename,text_num)
                temp.begin()
        elif opt in ("-t","--test"):
            text_num=int(arg)
    for i in arg:  #为进度条留下空行
        print()